package com.lujianfei.router_api

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.util.Log
import androidx.fragment.app.Fragment

class Router private constructor() {
    object FragmentKey {
        const val HOME = "/business/home"
        const val ME = "/business/me"
    }
    companion object {
        const val TAG = "Router"
        private var mApplication: Application ?= null
        private val routers = HashMap<String,Class<out Activity>>()
        private val fragmentRouters = HashMap<String,Fragment>()
        val instance = Router()
        fun initRouter(application: Application) {
            this.mApplication = application
            register("com.lujianfei.business.router.HomeRouter")
            register("com.lujianfei.business.router.MeRouter")
        }
        private fun register(className:String) {
            val forName = Class.forName(className)
            val moduleInstance = forName.newInstance()
            if (moduleInstance is IRouterLoad) {
                val iRouterLoad = moduleInstance as IRouterLoad
                iRouterLoad.apply {
                    loadInto(routers)
                    loadFragmentInto(fragmentRouters)
                }
            }
        }
    }

    /**
     * <out T> 等价于 java <? extends T>
     */
    fun register(key:String,cls:Class<out Activity>) {
        routers[key] = cls
    }

    fun registerFragment(key:String,fragment:Fragment) {
        fragmentRouters[key] = fragment
    }

    fun startActivity(key:String) {
        if (routers.containsKey(key)) {
            mApplication?.startActivity(Intent(mApplication,routers[key]).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        }
    }

    fun getFragment(key:String):Fragment? {
        if (fragmentRouters.containsKey(key)) {
            return fragmentRouters[key]
        }
        return null
    }
}

